﻿using UnityEngine;
using System.Collections;

public class CamDOF : MonoBehaviour {
	// Using camera
	// Lens: 35 mm
	// Vertical: 24 mm
	// Horizontal: 36 mm
	// => Diagonal: 43.3 mm
	
	public Texture2D  btnZoom;
	private float alpha = 60.0f;	// angle of view in radian
	private float f = 50.0f; 		// focal length: 12 - 200 mm
	private float d = 43.3f; 		// diagonal from lens 35 mm about 43.3 mm


	// Using camera
	// Fstop: 1.4 - 22
	// Focus distance = 50 * focal length
		
	private int fStopIndex = 0;
	private float fStop = 2.0f;
	private float[] fstopList = {1.4f,2,2.8f,4,5.6f,8,11,16,22};
	
	public Texture2D btnAperture;
	private DepthOfFieldScatter dof = null;
	private float focalLength = 50.0f;

	void Start() {
		
		dof = gameObject.GetComponent<DepthOfFieldScatter>();
		// Convert focus distance from meter to milimeter
		// focalLength = dof.focalLength * 1000 / 50;
		
	}

	void Update() {
	
		// Handle focus
		if(Input.GetMouseButtonDown(0)) {
			RaycastHit hit;
			Ray ray = camera.ScreenPointToRay(Input.mousePosition);
			if(Physics.Raycast(ray, out hit)) {
				dof.focalLength = hit.distance;
				// Update focal length
				// focalLength = dof.focalLength * 1000 / 50;				
				// Update fstop
				// UpdateFstop();
			}
		}	
	}

	void UpdateFstop() {
	
		float changes = focalLength / dof.aperture;
		for(int i = 0; i < fstopList.Length - 1; ++i) {
			if(changes > fstopList[i] && changes < fstopList[i + 1]) {				
				float diff1 = Mathf.Abs(changes - fstopList[i]);
				float diff2 = Mathf.Abs(changes - fstopList[i + 1]);
				
				// choose closest value
				if(diff1 < diff2) {
					fStopIndex = i;
				} else {
					fStopIndex = i + 1;
				}
				break;
			}
		}
		
	}
		
	void OnGUI() {
	
		// ZOOM
		GUI.DrawTexture(new Rect(0, 0, 64, 64), btnZoom);
		GUI.Label(new Rect(70, 0, 300, 25), "Lens: " + f + " mm");
						
		// Use slider to zoom
		f = GUI.HorizontalSlider(new Rect(70, 30, 250, 30), f, 12, 200);
		alpha = 2 * Mathf.Atan(d / (2 * f));
		// convert alpha from radian to degree
		camera.fieldOfView = alpha * 180 / Mathf.PI;


		// F-stop
		GUI.Label(new Rect(70, 140, 300, 25), "F-stop: " + fStop);
		GUI.DrawTexture(new Rect(0, 140, 64, 64), btnAperture);
		fStopIndex = (int)GUI.HorizontalSlider(new Rect(70, 170, 250, 30), fStopIndex, 0, 8);
		fStop = fstopList[fStopIndex];
		dof.aperture = focalLength / fStop; 
	
	}
}